
package com.xiaoma.myaudience.biz.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore.Video;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.R.integer;
import com.xiaoma.myaudience.biz.adapter.RankingListAdapter;
import com.xiaoma.myaudience.biz.model.ActivityDetailInfoModel;
import com.xiaoma.myaudience.biz.model.RankingListModel;
import com.xiaoma.myaudience.biz.task.ActivitysQuitTask;
import com.xiaoma.myaudience.biz.task.AddEventTask;
import com.xiaoma.myaudience.biz.task.DataAsyncTask;
import com.xiaoma.myaudience.biz.task.RankingListTask;
import com.xiaoma.myaudience.biz.task.RankingMoreTask;
import com.xiaoma.myaudience.biz.util.Constant;
import com.xiaoma.myaudience.biz.view.LoadingListView;
import com.xiaoma.myaudience.biz.view.RefreshableView;
import com.xiaoma.myaudience.biz.view.RefreshableView.PullToRefreshListener;
import com.xiaoma.myaudience.util.PrefHelper;
import com.xiaoma.myaudience.util.activity.BaseActivity;
import com.xiaoma.myaudience.util.model.ModelUtils;

/**
 * 活动页面.
 * 
 */
public class RankingListActivity extends BaseActivity implements  OnItemClickListener, PullToRefreshListener{
    
    private static final String TAG = "RankingListActivity";
    private static final int DIALOG_REFRESH = 0;
    private static final int MENU_REFRESH = Menu.FIRST;
	private static final int DIALOG_ADD_EVENT = 1;
	private static final int DIALOG_ADD_EVENT_NO_LOGIN = 2;
	private static final int DIALOG_ADD_EVENT_ERROR = 3;

	private String mEventId;
	private String mErrorMsg;
	private ActivitysQuitTask mActivitysQuitTask;
	private RankingMoreTask mActivitysMoreTask;
    
    private RankingListTask mRankingListTask;
    private RankingListAdapter mAdapter;
    private String mIndex;
    private int mPosition;
    
	private AddEventTask mAddEventTask;
	private LoadingListView listView;
	
	private Map<String, Object> mObjMap;
	private List<Map<String, Object>> mList;
	private String mLine;
	private RefreshableView mRefreshableView;

	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_first_page);
        mRefreshableView = (RefreshableView) findViewById(R.id.refresh_view);
        mRefreshableView.setVisibility(View.VISIBLE);
        mRefreshableView.setOnRefreshListener(this, 1);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
        	mIndex = String.valueOf(bundle.getInt("tab_index"));
		}
    	listView = (LoadingListView) findViewById(R.id.hot_elv);
        
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	execute();
    }
    private void execute() {
    	 cancel();
    	 Map<String,String> cookie = new HashMap<String,String>();
 		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE1,""));
 		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE2,""));
 		cookie.put("url", mIndex);
    	 mRankingListTask = new RankingListTask(this, DataAsyncTask.TASK_RANKING, this);
    	 mRankingListTask.execute(cookie);
	}
    
    private void cancel() {
    	if (mRankingListTask != null) {
    		mRankingListTask.cancel(true, true);
        }
    	mRankingListTask = null;
    }

    private void initData(List<Map<String, Object>> objMap) {
    	if (objMap == null) {
			return ;
		}
    	mList = objMap;
    	mAdapter = new RankingListAdapter(this, mList);
    	listView.getListView().setAdapter(mAdapter);
    	//listView.notify();
    	listView.getListView().setOnItemClickListener(this);
    	getData(objMap);
    	
    	listView.getLoadingMoreButton().setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!listView.onClickDefaultMoreLayout()) {
					return;
				}
				startLoadingMoreTask();
			}
		});
    }
    
    private void getData(List<Map<String, Object>> objMap) {
    	int index = Integer.valueOf(mIndex);
    	int length = objMap.size();
    	if(length<1){
    		Tips("暂时没有排行数据");
    		return;
    	}
    	switch (index) {
		case 1:
			mLine = (String) objMap.get(length -1).get(RankingListModel.PARAM_STARLEVEL); 
			break;
		case 2:
			mLine = (String) objMap.get(length -1).get(RankingListModel.PARAM_MEMBERNUM); 
			break;
		case 3:
			mLine = (String) objMap.get(length -1).get(RankingListModel.PARAM_VIEWNUM); 
			break;

		default:
			break;
		}
    }
    
    private void startLoadingMoreTask() {
    	mActivitysMoreTask = new RankingMoreTask(RankingListActivity.this, DataAsyncTask.TASK_RANKING_MORE, RankingListActivity.this);
    	Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mIndex);
		cookie.put("line", mLine);
    	mActivitysMoreTask.execute(cookie);
    }
    
    private void showAddInfoDialog(final int string) {
		final Dialog dlg = new AlertDialog.Builder(RankingActivity.mContext).create();
		 Window window = dlg.getWindow();
		 dlg.show();
		 window.setContentView(R.layout.add_event_view_layout);
		 if (string == R.string.add_event_txt) {
			 ((TextView)window.findViewById(R.id.base_title_bar_title)).setText(R.string.add_event_title_xy);
		 }else {
			((TextView)window.findViewById(R.id.base_title_bar_title)).setText(R.string.activity_detail);
		 }
		 
		 View vcancel = window.findViewById(R.id.cancel_comments_back_original);
		 vcancel.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dlg.dismiss();
				}
		 });
		 window.findViewById(R.id.show_comments_back_original).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dlg.dismiss();
				if(string == R.string.add_event_txt) {
					//必填资料需填写
		  			if (!PrefHelper.getBoolean(RankingListActivity.this, "isfulluserinfo", false)) {
		  				showDialog(DIALOG_ADD_EVENT);
					} else {
						//资料都全，参加活动
						addEvent();
					}
				}
			}
		});
	}
    
    private void addEvent() {
		if (mAddEventTask != null) {
			mAddEventTask.cancel(true, true);
		}
		mAddEventTask = null;
		
		mAddEventTask = new AddEventTask(this, DataAsyncTask.TASK_ADD_EVENT, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mEventId);
		mAddEventTask.execute(cookie);
	}

    @Override
    public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
    	Map<String, Object> item = (Map<String, Object>) adapter.getItemAtPosition(position);
    	mPosition = position;
    	mEventId = ModelUtils.getStringValue(item, ActivityDetailInfoModel.PARAM_EVENTID);
    	mObjMap = item;
    	if (item != null) {
			String status = ModelUtils.getStringValue(item, ActivityDetailInfoModel.PARAM_STATUS);
			Boolean islogin = PrefHelper.getBoolean(RankingListActivity.this, Constant.LOGIN_ISLOGIN, false);
			if ("0".equals(status)) {
	    		mEventId = ModelUtils.getStringValue(item, ActivityDetailInfoModel.PARAM_EVENTID);
		  		if (islogin) {
		  			//已登录都给丫显示
		  			showAddInfoDialog(R.string.add_event_txt);
		  			return;
				} else {
					showDialog(DIALOG_ADD_EVENT_NO_LOGIN);
				}
			} else if ("3".equals(status) || "4".equals(status)) {
				if (islogin) {
					executeQuit();
				} else {
					showDialog(DIALOG_ADD_EVENT_NO_LOGIN);
				}
			}
		}
    }
    
    private void cancelQuit() {
		if (mActivitysQuitTask != null) {
			mActivitysQuitTask.cancel(true, true);
		}
		mActivitysQuitTask = null;
	}
    
    private void executeQuit() {
		cancelQuit();
		mActivitysQuitTask = new ActivitysQuitTask(this, DataAsyncTask.TASK_QUIT_EVENT, this);
		Map<String,String> cookie = new HashMap<String,String>();
		cookie.put(Constant.LOGIN_COOKIE1,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE1,""));
		cookie.put(Constant.LOGIN_COOKIE2,PrefHelper.getString(RankingListActivity.this,Constant.LOGIN_COOKIE2,""));
		cookie.put("url", mEventId);
		mActivitysQuitTask.execute(cookie);
	}
    
    
    @Override
    public boolean onCreateOptionsNeteaseMenu(Menu menu) {
//    	((AudienceMainActivity)getParent()).onCreateOptionsNeteaseMenu(menu);
//        menu.add(0, MENU_REFRESH, 0, R.string.menu_refresh).setIcon(R.drawable.ic_menu_refresh);
        
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (!((AudienceMainActivity) getParent()).onMenuItemSelected(featureId, item)) {
            switch (item.getItemId()) {
                case MENU_REFRESH:
                    execute();
                    break;
            }
        }
        return true;
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_REFRESH: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage(getText(R.string.refresh_button));
                dialog.setOnCancelListener(new OnCancelListener() {                    
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (mRankingListTask != null) {
                        	mRankingListTask = null;
                        }                        
                    }
                });
                return dialog;
            }
            
            case DIALOG_ADD_EVENT: {
                AlertDialog.Builder builder = new Builder(RankingActivity.mContext);
                builder.setPositiveButton(R.string.add_event_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	Intent intent = new Intent(RankingListActivity.this, UserInfoDetailActivity.class);
                    	RankingListActivity.this.startActivity(intent);
                    }
                }).
                setNegativeButton(R.string.add_event_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	
                    }
                }).setMessage(R.string.add_event_msg);
                return builder.create();
            }
            
            case DIALOG_ADD_EVENT_NO_LOGIN: {
            	AlertDialog.Builder builder = new Builder(RankingActivity.mContext);
            	builder.setMessage(R.string.login_please);
            	builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent= new Intent(RankingListActivity.this, LoginActivity.class);
						RankingListActivity.this.startActivity(intent);
					}
            	});
            	return builder.create();
            }
            
            case DIALOG_ADD_EVENT_ERROR: {
            	AlertDialog.Builder builder = new Builder(RankingActivity.mContext);
            	builder.setNegativeButton(R.string.add_event_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                    	
                    }
            	});
            	builder.setMessage(mErrorMsg);
            	return builder.create();
            }
        }
        return super.onCreateDialog(id);
    }
    
    public void refresh() {
        if (mRankingListTask != null) {
            cancel();
        }
        showDialog(DIALOG_REFRESH);        
    }
    
    private void addEventPorcess(Map<String, Object> map) {
		if (!"0".equals(ModelUtils.getStringValue(map, "code"))) {
			mErrorMsg = ModelUtils.getStringValue(map, "errorMsg");
			showDialog(DIALOG_ADD_EVENT_ERROR);
		} else {
			//弹出信息
			Map<String, Object> data = ModelUtils.getMapValue(map, "data");
			String nengLiang = ModelUtils.getStringValue(data, "nengliang");
			int i = Integer.valueOf(nengLiang);
			mErrorMsg = (i > 0 ? "参加成功，奖励" + i : "参加成功，消耗" + Math.abs(i)) + "能量";
			
			boolean verify = ModelUtils.getStringValue(mObjMap, RankingListModel.PARAM_VERIFY).equals("1") ? true : false;
			mList.remove(mPosition);
			mObjMap.put(RankingListModel.PARAM_STATUS, verify ? "3" : "4");
			mList.add(mPosition, mObjMap);
			mAdapter.notifyDataSetChanged();
			
			removeDialog(DIALOG_ADD_EVENT_ERROR);
			showDialog(DIALOG_ADD_EVENT_ERROR);
		}
	}
    
    private void quitEventProcess(Map<String, Object> objMap) {
		if (!"0".equals(ModelUtils.getStringValue(objMap, "code"))) {
			mErrorMsg = ModelUtils.getStringValue(objMap, "errorMsg");
			showDialog(DIALOG_ADD_EVENT_ERROR);
		} else {
			//弹出信息
			mErrorMsg = "退出成功";
			mList.remove(mPosition);
			mObjMap.put(RankingListModel.PARAM_STATUS, "0");
			mList.add(mPosition, mObjMap);
			mAdapter.notifyDataSetChanged();
			removeDialog(DIALOG_ADD_EVENT_ERROR);
			showDialog(DIALOG_ADD_EVENT_ERROR);
		}
	}
    
    @Override
    public void onPostExecute(int what, Object o) {
    	//停止顶部刷新动画
    	mRefreshableView.finishRefreshing();
        super.onPostExecute(what, o);
        switch (what) {
            case DataAsyncTask.TASK_RANKING:
            	List<Map<String, Object>> objMap = (List<Map<String, Object>>) o;
            	if (objMap == null) {
					listView.showLoadingFailed();
					return;
				}
            	listView.showListView();
                initData(objMap);
                break;
                
            case DataAsyncTask.TASK_ADD_EVENT:
        		Map<String, Object> objMaps = (Map<String, Object>) o;
    			addEventPorcess(objMaps);
    			break;
    			
            case DataAsyncTask.TASK_QUIT_EVENT:
        		Map<String, Object> map = (Map<String, Object>) o;
    			quitEventProcess(map);
    			break;	
    			
            case DataAsyncTask.TASK_RANKING_MORE:
            	if (o == null) {
            		listView.finishClickDefaultMoreLayout();
					return;
				}
            	List<Map<String, Object>> list =  (List<Map<String, Object>>) o;
            	if (list.size() == 0 || list.size() < 10) {
					listView.hideLoadingMoreLayout();
					return;
				}
            	mList.addAll(list);
            	getData(list);
            	mAdapter.notifyDataSetChanged();
            	listView.finishClickDefaultMoreLayout();
            	break;
        }
    }

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		execute();
	}
}
